package haoyc.handler;

import haoyc.config.SessionManagement;
import haoyc.entity.Response;
import haoyc.entity.User;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Memory
 * @version 1.0
 * @date 2021/11/22
 */

@Slf4j
@ChannelHandler.Sharable
public class UserLoginServerHandler extends SimpleChannelInboundHandler<User> {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Channel channel = ctx.channel();
        if (channel.isActive()) {
            ctx.close();
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, User user) {
        String name = user.getName();
        // ip - channel]
        SessionManagement.setChannel(name, ctx.channel());
        ctx.channel().writeAndFlush(new Response("200", name));
    }
}
